import { EventBus } from '@/store/index'
import { H5_TYPE } from '@/common/const-dif'
import { PAGE_TYPE } from '@/common/const'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { COMPONENT_TYPES, CONTROL_TYPES } from '@/common/const-wb'
import { EVENT_HOVER_TYPES } from '@/common/events'
import { getPxOVwByValue } from '@/store/utils'
import { copySiteData } from '@/common/site-data'

export const pageLoadAssets = {
  created() {
    EventBus.$off("completeLoadSiteData", this.onComplateLoadSiteData)
    EventBus.$on("completeLoadSiteData", this.onComplateLoadSiteData)
  },
  mounted() {
    if(this.frontData.isLocalSiteData) {
      this.onComplateLoadSiteData(copySiteData);
    }
  },
  methods: {
    onComplateLoadSiteData(data){
      this.siteData_ = data;
      this.loadJsAndCssByData();
    },
    loadAllAssets() {
      if(this.siteInfo.isDisplayAssetsLoading) {
        this.$store.commit("updateDisplayAssetsLoading", { isDisplayAssetsLoading: true })
      }
      if(this.siteAttrs.loadAssets) {
        const loadAssetses = this.siteAttrs.loadAssets.split(",");
        if(loadAssetses.length > 0) {
          const manifest = loadAssetses;
          // Create a preloader. There is no manifest added to it up-front, we will add items on-demand.
          const preload = new window.createjs.LoadQueue(false);
          preload.on("progress", this.onOverallProgress);
          preload.loadManifest(manifest);
        }
      }
    },
    onOverallProgress(event){
      let process = event.loaded * 100;
      EventBus.$emit('loadAssetsProcess', process);
      if(process >= 100){
        this.$store.commit("updateDisplayAssetsLoading", { isDisplayAssetsLoading: false })
        this.siteInfo.isLoadAssetsCompleteNotInitComp = true;
      }
    },
    loadJsAndCssByData(){
      let currentPage = this.siteData_.pages[0];
      let title = this.siteAttrs.share && this.siteAttrs.share.allShare ? this.siteAttrs.share.allShare.title : ''
      let scale = currentPage ? MOBILE_WID_HEI.clientWidth/currentPage.attrs.width/window.devicePixelRatio : 1
      let metas = [{ name: 'description', content: title }]
      if(this.siteAttrs.h5Type == H5_TYPE.pc && this.siteInfo.md.isMobile){
        metas.push({ name: 'viewport', content: 'width=device-width, initial-scale=' + scale + ', minimum-scale=0.3, maximum-scale=2.0, viewport-fit=cover, user-scalable=yes' })
      }else{
        // metas.push({ name: 'viewport', content: 'width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, viewport-fit=cover' })
      }
      let metaDom = document.getElementsByTagName('head')[0];
      _.forEach(metas, (meta) => {
        let newMetaDom = document.createElement("meta");
        newMetaDom.name = meta.name;
        newMetaDom.content = meta.content;
        metaDom.appendChild(newMetaDom);
      })

      let titleDom = document.getElementsByTagName('title')[0];
      titleDom.innerHTML = title;

      const webUrl = this.env.baseUrl
      let links = [{ rel: 'stylesheet', href: webUrl + 'css/iconfont.css?v=1' }]
      // if(this.isLoadJsObj.isAnimate || this.siteAttrs.isRandomEffect || this.siteAttrs.isPopRandomEffect){
      //   links.push({ rel: 'stylesheet', href: webUrl + 'css/animate.min.css?v=2' })
      // }
      // if(this.isLoadJsObj.isCustomFont){
        // links.push({ rel: 'stylesheet', href: webUrl + 'css/custom_font.css?v=8' })
      // }
      if(this.isLoadJsObj.isDefaultFont){
        links.push({ rel: 'stylesheet', href: webUrl + 'css/fonts.css' })
      }
      if(this.isLoadJsObj.isSwiper){
        links.push({ rel: 'stylesheet', href: webUrl + 'css/swiper-bundle.min.css?v=7' })
      }
      let scripts = []
      let scripts_ = []//需要在普通js加载完后在加载的js
      if(this.siteAttrs.loadAssets) {
        const loadAssetses = this.siteAttrs.loadAssets.split(",");
        if(loadAssetses.length > 0) {
          scripts.push({ src: webUrl + 'js/createjs/preloadjs-NEXT.min.js', type: 'text/javascript', charset: 'utf-8'})
        }
      }
      if(this.isLoadJsObj.isCreatejs){
        scripts.push({ src: webUrl + 'js/createjs/createjs.min.js', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isEaseljs){
        scripts.push({ src: webUrl + 'js/createjs/easeljs-NEXT.min.js', type: 'text/javascript', charset: 'utf-8'})
        scripts.push({ src: webUrl + 'js/createjs/preloadjs-NEXT.min.js', type: 'text/javascript', charset: 'utf-8'})
        scripts.push({ src: webUrl + 'js/createjs/tweenjs-NEXT.min.js', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isPixi){
        scripts.push({ src: webUrl + 'js/pixi/pixi.min.js', type: 'text/javascript', charset: 'utf-8'})
        if(this.isLoadJsObj.isGsap) {
          scripts.push({ src: webUrl + 'js/gsap/PixiPlugin.min.js', type: 'text/javascript', charset: 'utf-8'})
        }
        if(this.isLoadJsObj.isPixiFilters) {
          scripts_.push({ src: webUrl + 'js/pixi/pixi-filters.js', type: 'text/javascript', charset: 'utf-8'})
        }
      }
      if(this.isLoadJsObj.isThree){
        scripts.push({ src: webUrl + 'js/threejs/three.min.js', type: 'text/javascript', charset: 'utf-8'})
        if(this.isLoadJsObj.isOrbitControls){
          scripts_.push({ src: webUrl + 'js/threejs/controls/OrbitControls.js', type: 'text/javascript', charset: 'utf-8'})
        }
        if(this.isLoadJsObj.isGltfLoader) {
          scripts_.push({ src: webUrl + 'js/threejs/loaders/GLTFLoader.js', type: 'text/javascript', charset: 'utf-8'})
        }
      }
      if(this.isLoadJsObj.isSwiper){
        scripts.push({ src: webUrl + 'js/swiper-bundle.min.js?v=7', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isMoveable){
        scripts.push({ src: webUrl + 'js/fabric/fabric.min.js?v=2', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isShake){
        scripts.push({ src: webUrl + 'js/shake.js', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isHtml2canvas){
        scripts.push({ src: webUrl + 'js/html2canvas.min.js?v=4', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isScanQRCode){
        scripts.push({ src: webUrl + 'js/weibo.js?v=2', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isPhaser){
        scripts.push({ src: webUrl + 'js/phaser/phaser.min.js?v=2', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isJsBarcode){
        scripts.push({ src: webUrl + 'js/JsBarcode.all.min.js?v=1', type: 'text/javascript', charset: 'utf-8'})
        scripts.push({ src: webUrl + 'js/base64.js', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isSvgAnimate){
        scripts.push({ src: webUrl + 'js/svg/vivus.min.js', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isSvga){
        scripts.push({ src: webUrl + 'js/svg/svga.min.js', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isSlotMachine){
        scripts.push({ src: webUrl + 'js/slotmachine/slotmachine.js?v=1', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isPaper){
        scripts.push({ src: webUrl + 'js/paper/paper-full.min.js', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isGsap || _.size(this.animates.isGroupGsap) > 0 || _.size(this.animates.isGsap) > 0 || _.size(this.animates.isScrollTriggerGsap) > 0){
        scripts.push({ src: webUrl + 'js/gsap/gsap.min.js?v=7', type: 'text/javascript', charset: 'utf-8'})
      }
      if(_.size(this.animates.isPathBezier) > 0 || this.isLoadJsObj.isGsapBezier){
        scripts.push({ src: webUrl + 'js/gsap/MotionPathPlugin.min.js?v=7', type: 'text/javascript', charset: 'utf-8'})
      }
      if(_.size(this.animates.isSplitGsap)){
        scripts.push({ src: webUrl + 'js/gsap/SplitText.min.js?v=7', type: 'text/javascript', charset: 'utf-8'})
      }
      if(_.size(this.animates.isScrollTriggerGsap) > 0){
        scripts.push({ src: webUrl + 'js/gsap/ScrollTrigger.min.js?v=7', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isVideo){
        if(this.siteInfo.md.isIPhone){
          scripts.push({ src: webUrl + 'js/iphone-inline-video.min.js', type: 'text/javascript', charset: 'utf-8'})
        }
        scripts.push({ src: webUrl + 'js/DPlayer.min.js', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isAudio){
        scripts.push({ src: webUrl + 'js/APlayer.min.js?v=1', type: 'text/javascript', charset: 'utf-8'})
      }
      if(this.isLoadJsObj.isMatter){
        scripts.push({ src: webUrl + 'js/matter.min.js', type: 'text/javascript', charset: 'utf-8'})
      }

      if(this.isLoadJsObj.isTurnBook){
        scripts.push({ src: webUrl + 'js/turn/jquery.min.1.7.js', type: 'text/javascript', charset: 'utf-8'})
      }

      this.scriptsTotal = scripts.length;
      this.loadScriptCount = 0;
      _.forEach(scripts, (script) => {
        this.loadCssOrScript(script.src, this.loadCompleteCallback)
      })
      _.forEach(links, (link) => {
        this.loadCssOrScript(link.href)
      })
      if(scripts.length == 0){
        this.loadCompleteCallback()
      }

      if(scripts_.length > 0) {
        this.scripts_ = scripts_;
        this.isLoadScript_ = true;
      }
    },
    loadCssOrScript(url, fn) {
      let Head = document.getElementsByTagName('head')[0];
      let linkScript;
      /* eslint-disable */
      if(/\.css[^\.]*$/.test(url)) {
        linkScript = document.createElement("link");
        linkScript.type = "text/" + ("css");
        linkScript.rel = "stylesheet";
        linkScript.href = url;
      } else {
        linkScript = document.createElement("script");
        linkScript.type = "text/" + ("javascript");
        linkScript.src = url;
      }
      Head.insertBefore(linkScript, Head.lastChild)
      linkScript.onload = linkScript.onerror = function() {
        if(fn) fn()
      }
    },
    loadCompleteCallback(){
      this.loadScriptCount++;
      if(this.loadScriptCount >= this.scriptsTotal){
        if(this.isLoadScript_ && this.scripts_.length > 0){
          this.isLoadScript_ = false;
          this.loadScriptCount = 0;
          this.scriptsTotal = this.scripts_.length;
          _.forEach(this.scripts_, (script) => {
            this.loadCssOrScript(script.src, this.loadCompleteCallback)
          })
          return;
        }
        this.store.dispatch("setSitePages", this.siteData_);
        const loadAssetses = this.siteAttrs.loadAssets.split(",");
        if(this.siteInfo.isDisplayAssetsLoading || loadAssetses.length > 0) {
          this.loadAllAssets();
        }
        this.addScrollTriggerAnimate();
        // this.setFollowData();
        this.setHtml2canvasUploadData();
        this.initCssVar();
      }
    },
    initCssVar() {
      let arr = [-2,-4,-6,-8,-20,-26,-28,-30,-32,-36,-40,-50,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,48,50,52,54,56,58,60,70,80,84,90,72,78,100,106,108,120,132,136,150,156,170,190,192,230,300,330,420,450,500,510,750];
      let docStyle = document.documentElement.style;
      _.forEach(arr, (num) => {
        docStyle.setProperty(`--size-${num}`, getPxOVwByValue(num));
      })
      let initAPLayerCssObj = {
        "aplayer-author-size": 24,
        "aplayer-title-size": 28,
        "aplayer-lrc-height": 70,
        "aplayer-lrc-size": 24,
        "aplayer-lrc-line-height": 48,
        "aplayer-lrc-active-size": 28,
        "aplayer-pic-top": 100,

        "van-padding-base": 4,
        "van-padding-xs": 8,
        "van-padding-sm": 12,
        "van-padding-md": 16,
        "van-padding-lg": 24,
        "van-padding-xl": 32,

        "van-font-size-xs": 10,
        "van-font-size-sm": 12,
        "van-font-size-md": 14,
        "van-font-size-lg": 16,
        "van-line-height-xs": 14,
        "van-line-height-sm": 18,
        "van-line-height-md": 20,
        "van-line-height-lg": 22,

        "van-border-width-base": 1,
        "van-border-radius-sm": 2,
        "van-border-radius-md": 4,
        "van-border-radius-lg": 8,
        "van-border-radius-max": 999,

        "van-font-size-lg": 32,
        "van-font-size-md": 28,
        "van-font-size-sm": 24,
        "van-field-text-area-min-height": 12,
        "van-calendar-header-title-height": 88,
        "van-calendar-day-height": 128,
        "van-calendar-month-mark-font-size": 320,
        "van-calendar-weekdays-height": 60,
        "van-calendar-selected-day-size": 108,
        "van-calendar-confirm-button-height": 72,
        "van-dropdown-menu-height": 48,

        "van-uploader-size": 160,
        "van-uploader-icon-size": 48,
        "van-uploader-delete-icon-size": 28,
        "van-uploader-file-icon-size": 40,
        "van-uploader-mask-icon-size": 44,
        "van-uploader-loading-icon-size" : 44,

        "van-button-mini-height": 48,
        "van-button-small-height": 64,
        "van-button-large-height": 100,
        "van-button-default-height": 88,
        "van-button-loading-icon-size": 40,

        "van-toast-icon-size": 72,
        "van-toast-text-min-width": 192,
        "van-toast-default-width": 176,
        "van-toast-default-min-height": 176,

        "van-checkbox-size": 40,
        "van-radio-size": 40,
        "van-field-icon-size": 32,
        "van-field-clear-icon-size": 32,
        "van-field-error-message-font-size": 24,
        // "van-field-text-area-min-height": 120,
        "van-field-word-limit-line-height": 32,
        "van-address-list-item-font-size": 26,
        "van-address-list-edit-icon-size": 40,

        "van-switch-size": 60,
        "van-loading-spinner-size": 60,

        "van-dialog-width": 640,
        "van-dialog-border-radius": 32,
        "van-dialog-header-line-height": 48,
        "van-dialog-header-padding-top": 52,
        "van-dialog-button-height": 96,
        "van-dialog-round-button-height": 72,
        "van-dialog-message-font-size": 32
      }
      _.forEach(initAPLayerCssObj, (num, key) => {
        docStyle.setProperty(`--${key}`, getPxOVwByValue(num));
      })
    },
    setFollowData() {
      if(this.globalIsPost.followCompIds && this.globalIsPost.followCompIds.length > 0) {
        // https://apib.hd.xxx.com/v1/feinit/wb_friendship?site_id=1&uidb=B
        const followCompIds = this.globalIsPost.followCompIds;
        let timeout = 100;
        _.forEach(followCompIds, (followCompId) => {
          let wbData = this.controls[followCompId] && this.controls[followCompId][CONTROL_TYPES.wb_follow]
          if(wbData && wbData.data.follow_uid){
            window.setTimeout(() => {
              this.post('/feinit/wb_friendship', { uidb : wbData.data.follow_uid , type: 'displayFollowComponent', item: { id: followCompId }})
            }, timeout)
            timeout = timeout + 100;
          }
        })
      }
    },
    setHtml2canvasUploadData() {
      if(this.isLoadJsObj.isNeedUploadParams) {
        let event = { type: EVENT_HOVER_TYPES.saveImg.type }
        this.initPost('/file/params', {event});
      }
    },
    addScrollTriggerAnimate() {
      if(_.size(this.animates.isSplitGsap) > 0 || (_.size(this.animates.isAnimate) > 0 || _.size(this.animates.isGroupGsap) > 0 || _.size(this.animates.isGsap) > 0) && this.siteAttrs.pageType == PAGE_TYPE.long){
        window.addEventListener('scroll', _.throttle(this.onScrollPlayAnimate, 200));
        // window.addEventListener('scroll', this.onScrollPlayAnimate);
      }
    },
    onScrollPlayAnimate(){
      if(this.statePopId > 0){
        return;
      }
      let pageId = "page-" + (this.pageIndex+1);
      const currentPageDom = document.getElementById(pageId);
      if(currentPageDom){
        this.playAnimates(currentPageDom);
        if(window.gsap){
          this.kindsGsaps(window.gsap, currentPageDom);
        }
      }
    },
  },
  beforeUnmount(){
    EventBus.$off("completeLoadSiteData", this.onComplateLoadSiteData)
  }
}
